var imageInfo = null;
var curCheckCode = ''; // check code
var imageIDs = []; // this contains all image id, is is the image url
var series = []; // contain the series information
var seriesArray = []; // Contain series and isntances information
var loaded = []; // Is the image loaded
var multiSeries = []; // is multi series
var loadedIndex = []; // Indicate each window loaded series
var clickedSeries = -1;
var rangeMin = 0; // for input range
var rangeMax = 0;
var synchronizer = null;
var reportFlag = '';
var sort = 0;
var image2askid = '';
var iWindowVNum = 1;
var iWindowHNum = 1;
var patId = 0;
var studyUID = 0;
var imageType = "jpg";
var totalSeries = 0;
var isMobile = $.browser.mobile;
var isDesktop = $.browser.desktop;
var askId = '';
var imageId = null;
var imageInfo = null;
var countser = 0;
var groupIndex = [];
var iSeriesNum = 0; // total series number
var locations = []; // each series location
var thickness = []; // each series thickness
var groupNum = 0; // the number of the groups, in each of which the series are synchronizers
var orientation = []; // each series orientation
var firwidth = 0;
var changgeSeriesByIndex = -1;
var synchronizers = [];
var synchrSwitch = false;
var viewportNum = 0; // total viewport number
var dis = true;
var elementChoosed = ''; // current element in canvas which is clicked
var initialWW = []; // initial window width of every instance
var initialWL = []; // initial window level of every instance
var globalWW = 0; // on mobile, when the window width of current image is modified, it is saved in "globalWW"
var globalWL = 0; // on mobile, when the window center of current image is modified, it is saved in "globalWL"
var contrastButtonPressed = false; // to judge whether the "enableWindowLevelTool" button has been pressed
var referenceLineButtonPressed = false; // to judge whether the "referenceLine" button has been pressed
var curImageID = ''; // currrent image id
var curCheckCode = ''; // check code
var isloaded = 0;
var eformid = null;

//这里面是为适应特定功能临时添加的变量，待分享与常规阅片的显像代码（imageShow.js）同步后需要整合的
//--------------- Updated by TanQilu
/********************************* start **************************************/
var tags = [];
var tagArray = []; // contain instances tags
var wheelInstanceNum = []; // used to display the current instance number according to mouse wheel
var autoPlayButtonPressed = true;
var wheelInstanceNum = []; // used to display the current instance number according to mouse wheel
/********************************* end **************************************/

$(function() {
	
	// Dynamically distinguish if javascript code for mobile shuold
	// be loaded.
	if (isMobile) {
		var oHead = document.getElementsByTagName('HEAD').item(0);
		var oScript = document.createElement("script");
		oScript.type = "text/javascript";
		oScript.src = '/imagecloud/js/touch-emulator.js';
		oHead.appendChild(oScript);
		$('#').hide();
	}
	
	if(isMobile){
		$('#pageUp').click(function(e) {
			var index = parseInt(curImageNum, 10);    
            index = index - 1;                  
            index = index > -1 ? index : 0;
            
             if(contrastButtonPressed && navigator.userAgent.indexOf('iPhone' ) == -1){
                  readjustInstanceWWWL(index);
            } else {
                  selectNewImage(index);
            }
		/*	var index = parseInt(curImageNum, 10);	
			index = index - 1;			
			selectNewImage(index);		*/
		});
		
		$('#pageDown').click(function(e) {
			var index = parseInt(curImageNum, 10);    
            index = index + 1;      
            index = index < seriesArray[sort].instance.length ? index : seriesArray[sort].instance.length-1;
            
             if(contrastButtonPressed && navigator.userAgent.indexOf('iPhone' ) == -1){
                  readjustInstanceWWWL(index);
            } else {
                  selectNewImage(index);
            }      
		/*	var index = parseInt(curImageNum, 10);	
			index = index + 1;			
			selectNewImage(index);		*/
		});
	}
	
	//这里面是为适应特定功能临时添加的代码，待分享与常规阅片的显像代码（imageShow.js）同步后需要整合的
	// --------------- Updated by TanQilu
	/*****************************************start*****************************************/
	// this function is used to autoplay images------------------ Updated by TanQilu
	var circulation = new Function();
	$('#autoPlay').click(function(){
		if(iWindowHNum*iWindowHNum != 1){
			humane.log('仅支持单窗口阅片');
			return;
		}	
		if(autoPlayButtonPressed){
			autoPlayButtonPressed = false;
			clearInterval(circulation);
			
			var element = $('#image00').get(0);
			wheelInstanceNum[0] = getImgIndex(element).instance;
			var seriesIndex = getImgIndex(element).series;
			circulation = setInterval(function(){
				selectNewImage(wheelInstanceNum[0]);
					wheelInstanceNum[0]++;
					if(wheelInstanceNum[0]>=seriesArray[seriesIndex].instance.length){
						wheelInstanceNum[0] = 0;
					}
				},100);	
		} else {
			autoPlayButtonPressed = true;	
			clearInterval(circulation);
		}
	});
	
	// get the series number and instance number of the element---------------- Updated by TanQilu
	function getImgIndex(element/*optional*/,image/*optional*/){
		var imgNum = '';
		var instanceNum = 0;
		var startIdx = 0;
		var endIdx = 0;
		var seriesId = '';
		var seriesNum = '';
		
		if(element != undefined){
			// find the instanceNum
			imgNum = element.children[2].innerHTML.split('<br>')[0].split('：')[1];
			instanceNum = parseInt(imgNum.split('/')[0])-1;
			
			// find the seriesId
			startIdx = cornerstone.getImage(element).imageId.indexOf('series') + 7;
			endIdx = cornerstone.getImage(element).imageId.indexOf('&object');
			seriesId = cornerstone.getImage(element).imageId.substring(startIdx,endIdx);
		}
		
		if(image != undefined){		
			// find the seriesId
			startIdx = image.imageId.indexOf('series') + 7;
			endIdx = image.imageId.indexOf('&object');
			seriesId = image.imageId.substring(startIdx,endIdx);
		}
			
		// find the seriesNum
		for(var i = 0; i < seriesArray.length; i++){
			if(seriesId == seriesArray[i].seriesUID){
				seriesNum = i;
				break;
			}
		}
		
		if(image != undefined){
			// find the instanceNum this image
			var idStart = image.imageId.indexOf('object=')+7;
			var idEnd = image.imageId.indexOf('&rows');
			var objectId = image.imageId.substring(idStart,idEnd);
			
			for(var i=0; i<seriesArray[seriesNum].instance.length; i++){
				if(objectId == seriesArray[seriesNum].instance[i].sopIUID){
					instanceNum = i;
					break;
				}
			}
		}
		
		var imgIndex = {
				instance: instanceNum,
				series:   seriesNum
		}
		return imgIndex;
	}
	/******************************************end****************************************/

	// Configure the notification
	notifyConfigure();

	// Get configuration parameters
	var hostport = document.location.host;
	// hosturl = 'http://chenzhijun:8888';
	hosturl = 'http://123.56.201.253:8888';

	lmViewer.srv.service_ImageViewer_getConfig(data,function(data){
		var urls = data.message.split(";");

		// load image
		dcmurl = urls[0];
		serverURL = urls[1];
		queryString = window.location.href;
		patId = getParameter(queryString, "patientID");
		studyUID = getParameter(queryString, "studyUID");
		imageType = getParameter(queryString, "type");

		if(isMobile){
			imageType = "jpg";
		}

		if(isDesktop){
			imageType = "dicom";
		}

		if (validataOS()=='Mac'){
			imageType = "jpg";
		}

		reportFlag = getParameter(queryString, "reportFlag");
		image2askid = getParameter(queryString, "image2askid");
		if (null == image2askid || '' == image2askid
			|| 'null' == image2askid) {
			$("#li_tab2").css("display", "none");
		}
		askId = getParameter(queryString, "askId");
		imageId = getParameter(queryString, "imageid");

		totalSeries = 0;
		if(isDesktop === true){
			$('#enableScrollStack').css('display','none');
		}

		cancelBindKey();
		loadButtonHint();

		iWindowVNum = 1;
		iWindowHNum = 1;

		//当影像共享从报告单二维码扫描传递的 eformid
		// Get studyUI from eformid
		eformid = getParameter(queryString, "eformid");
		retrieveShare(hosturl, patId, studyUID, dcmurl);

		window.addEventListener('resize', resizeCanvas, false);
	},function(data){
		humane.log("影像服务器连接错误，请联系客服。", {
			timeout : 4000,
			clickToClose : true,
			addnCls : 'humane-error'
		});
	});
/*	$.ajax({
		url : hosturl + '/imagecloud/service/ImageViewer/getConfig',
		type : 'get',
		data : {},

		dataType : 'json',
		success : function(data) {

			var urls = data.message.split(";");

			// load image
			dcmurl = urls[0];
			serverURL = urls[1];
			queryString = window.location.href;
			patId = getParameter(queryString, "patientID");
			studyUID = getParameter(queryString, "studyUID");
			imageType = getParameter(queryString, "type");
			
			if(isMobile){
				imageType = "jpg";
			}
			
			if(isDesktop){
				imageType = "dicom";
			}
			
			if (validataOS()=='Mac'){
				imageType = "jpg";
			}
			
			reportFlag = getParameter(queryString, "reportFlag");
			image2askid = getParameter(queryString, "image2askid");
			if (null == image2askid || '' == image2askid
					|| 'null' == image2askid) {
				$("#li_tab2").css("display", "none");
			}
			askId = getParameter(queryString, "askId");
			imageId = getParameter(queryString, "imageid");
			
			totalSeries = 0;
			if(isDesktop === true){
				$('#enableScrollStack').css('display','none');
			}
			
			cancelBindKey();
			loadButtonHint();
			
			iWindowVNum = 1;
			iWindowHNum = 1;
			
			//当影像共享从报告单二维码扫描传递的 eformid
			// Get studyUI from eformid
			eformid = getParameter(queryString, "eformid");
			retrieveShare(hosturl, patId, studyUID, dcmurl);
			
			window.addEventListener('resize', resizeCanvas, false);
		},
		error : function(data) {
			humane.log("影像服务器连接错误，请联系客服。", {
				timeout : 4000,
				clickToClose : true,
				addnCls : 'humane-error'
			});
		}
	});*/
});

function validataOS(){
	if(navigator.userAgent.indexOf('Window')>0){
	     return 'Windows';
	}else if(navigator.userAgent.indexOf('Mac OS X')>0) {
	     return 'Mac ';
	}else if(navigator.userAgent.indexOf('Linux')>0) {
	     return 'Linux';
	}else{
	     return 'NUll';
	}
}

/**
 * Initialize dicom image viewer
 * 
 * @Ryan Zhang 2015-05-24
 */
function retrieveShare(hosturl, patId, studyUID, dcmurl) {
	
	//当影像共享从报告单二维码扫描传递的 eformid 参数查看影像
	if(eformid !="null" && eformid !=null && eformid !=''){
        var data = {
			eformid:eformid
		};
		lmViewer.srv.service_eformimage_eformid(data,function(){
			var result = data.result;
			if (result == 0) {
				var eformInfo = data.message;
				curImageID = eformInfo.imageid;

				var params = {
					imageId:curImageID
				};
				// get image information
				lmViewer.srv.service_image_imageId(params,function(data){
					var message = data.message;
					var displayText = '拍摄机构：' + '&nbsp'
						+ message.institutionname + '<br/>'
						+ '患者姓名：' + '&nbsp'
						+ message.patientname;
					if (message.sex == 0) {
						displayText += ' ，男';
					} else {
						displayText += ' ，女';
					}
					displayText += '<br/>';
					displayText += '拍摄时间：' + '&nbsp'
						+ message.studydate;
					imageInfo = message;

					iWindowVNum = 1;
					iWindowHNum = 1;

					isloaded = 1;

					retrieveImage(hosturl, curImageID);

					// show the content
					var content = document.getElementById("content-forwrap");
					content.style.display = "block";
				},function(data){
					humane.log("影像服务器连接错误，请联系客服。");
				});

			}
		},function(data){
			humane.log("影像服务器连接错误。Cannot connect server to get the series information.");
		});

		/*$.ajax({
				url : hosturl + '/imagecloud/service/eformimage/' + eformid
						+ '?eformid=' + eformid,
				type : 'get',
				dataType : 'json',
				success : function(data) {
					var result = JSON.parse(data.result);
					if (result == 0) {
						var eformInfo = JSON.parse(data.message);
						curImageID = eformInfo.imageid;
						// get image information
						$.ajax({
							url : hosturl + '/imagecloud/service/image/'
									+ curImageID,
							type : 'get',
							data : {},
							dataType : 'json',
							success : function(data) {

								var message = parseMessageData(data.message);
								var displayText = '拍摄机构：' + '&nbsp'
										+ message.institutionname + '<br/>'
										+ '患者姓名：' + '&nbsp'
										+ message.patientname;
								if (message.sex == 0) {
									displayText += ' ，男';
								} else {
									displayText += ' ，女';
								}
								displayText += '<br/>';
								displayText += '拍摄时间：' + '&nbsp'
										+ message.studydate;
								imageInfo = message;

								iWindowVNum = 1;
								iWindowHNum = 1;

								isloaded = 1;
								
								retrieveImage(hosturl, curImageID);
								
								// show the content
								var content = document.getElementById("content-forwrap");
								content.style.display = "block";
							},
							error : function(data) {
								humane.log("影像服务器连接错误，请联系客服。");
							}
						});
					}
				},
				error : function(data) {
					humane.log("影像服务器连接错误。Cannot connect server to get the series information.");
				}
			});*/
	// 否则影像共享通过直接传递的是 imageid 参数查看影像
	}else{
		// get image information
		var params = {
			imageId:imageId
		};
		lmViewer.srv.service_image_imageId(params,function(data){
			var message = parseMessageData(data.message);
			var displayText = '拍摄机构：' + '&nbsp'
				+ message.institutionname + '<br/>'
				+ '患者姓名：' + '&nbsp'
				+ message.patientname;
			if (message.sex == 0) {
				displayText += ' ，男';
			} else {
				displayText += ' ，女';
			}
			displayText += '<br/>';
			displayText += '拍摄时间：' + '&nbsp'
				+ message.studydate;
			imageInfo = message;

			iWindowVNum = 1;
			iWindowHNum = 1;

			isloaded = 1;

			retrieveImage(hosturl, imageId);

			// show the content
			var content = document.getElementById("content-forwrap");
			content.style.display = "block";
		},function(data){
			humane.log("影像服务器连接错误，请联系客服。");
		});


/*		$.ajax({
			url : hosturl + '/imagecloud/service/image/'+ imageId,
			type : 'get',
			data : {},
			dataType : 'json',
			success : function(data) {

				var message = parseMessageData(data.message);
				var displayText = '拍摄机构：' + '&nbsp'
						+ message.institutionname + '<br/>'
						+ '患者姓名：' + '&nbsp'
						+ message.patientname;
				if (message.sex == 0) {
					displayText += ' ，男';
				} else {
					displayText += ' ，女';
				}
				displayText += '<br/>';
				displayText += '拍摄时间：' + '&nbsp'
						+ message.studydate;
				imageInfo = message;

				iWindowVNum = 1;
				iWindowHNum = 1;

				isloaded = 1;
				
				retrieveImage(hosturl, imageId);
				
				// show the content
				var content = document.getElementById("content-forwrap");
				content.style.display = "block";
			},
			error : function(data) {
				humane.log("影像服务器连接错误，请联系客服。");
			}
		});*/
	}
}

function retrieveImage(hosturl, imageid) {
	$.ajax({
			url : hosturl + '/imagecloud/service/image/' + imageid,
			type : 'get',
			dataType : 'json',
			success : function(data) {
				var imageInfo = JSON.parse(data.message);

				patId = imageInfo.patientid;
				studyUID = imageInfo.studyid;
				//读图加载影像
				loadStudy(hosturl, patId, studyUID, dcmurl,serverURL);
			},
			error : function(data) {
				humane.log("影像服务器连接错误。Cannot connect server to get the series information.",
				{
					timeout : 1000,
					clickToClose : true,
					addnCls : 'humane-error'
				});
			}
	});
}

//resize the canvas to fit the image
function resizeCanvas() {
	$('#slice-range').css('display','none');
	var clientWidth = document.body.clientWidth;
	var clientHeight = document.body.clientHeight;
	if(clientWidth > clientHeight){
		$('#vertical').css('display','block'); 		
		$('#transverse').css('display','none'); 
		$(' #contentDiv').parent().css( 'position', 'absolute');    
        
        var width = (document.body.clientWidth - $('#vertical' ).width()-10).toString() + 'px' ;
        $(' #contentDiv').parent().css( 'width', width.toString()); 
	}else{
		$('#vertical').css('display','none');
		$('#transverse').css('display','block'); 
		$('#contentDiv').parent().css( 'position', ""); 
	}
	
	var cnt = parseInt('0');
	var test = 0;

	if(clientWidth > clientHeight){
  	  document.getElementById( "imageContainer").style.width =
            (document.body.clientWidth - $('#vertical' ).width()).toString() + 'px' ;
    } else {
  	  document.getElementById( "imageContainer").style.width =
            document.body.clientWidth.toString() + 'px' ;
    }
	
	for (var x = 0; x < iWindowHNum; x++) {
		for (var y = 0; y < iWindowVNum; y++) {

			var imageDivId = "image" + x.toString() + y.toString();
			var element = $('#' + imageDivId).get(0);

			if (element === undefined) {
				continue;
			}

			var enabledElement = cornerstone.getEnabledElement(element);
			var currCanvas = enabledElement.canvas.getContext('2d').canvas;

			var totalWidth = $('#imageContainer' ).width()-1-iWindowVNum-2*iWindowVNum;
            var totalHeight = document.body.clientHeight - $('#app-nav').height() - $( '#tabs1').height()-6-5*iWindowHNum-2*iWindowHNum;

            if(isMobile){
         	   if(clientWidth > clientHeight) { 
         		   //横屏                		   
         		   $(' #contentDiv').parent().css( 'left', '');
         		   $(' #contentDiv').parent().css( 'padding-left', '0px');
         		   $(' #vertical').css('padding-left', '');
         		   document.getElementById( "imageContainer").style.width =
         	              (document.body.clientWidth - $('#series' ).width()).toString() + 'px' ; 
         		   var width = ($(' #imageContainer').width()).toString() + 'px';
         		   $(' #toolBar').css('width', width);
         		   totalHeight = document.body.clientHeight - $('#app-nav').height() - $( '#tabs1').height() - 7;
         	   } else {
         		   //竖屏                		   
         		   $(' #contentDiv').parent().css( 'left', '');
         		   $(' #contentDiv').parent().css( 'width', '');
         		   $(' #contentDiv').parent().css( 'padding-left', '');
         		   document.getElementById( "imageContainer").style.width =
         	              document.body.clientWidth.toString() + 'px' ;        
         		   var width = ($(' #imageContainer').width()).toString() + 'px';
         		   $(' #toolBar').css('width', width);
         		   totalHeight = document.body.clientHeight - $('#app-nav').height() - $( '#tabs1').height() - $('#transverse' ).height() - 7;
         	   }                        
           }

            currCanvas.width = Math.floor(totalWidth / iWindowVNum);
            currCanvas.height = Math.floor(totalHeight / iWindowHNum);
            var iWidth = Math.floor(totalWidth / iWindowVNum);
            var iHeight = Math.floor(totalHeight / iWindowHNum);

			currCanvas.style.width = iWidth.toString() + 'px';
			currCanvas.style.height = iHeight.toString() + 'px';
			cornerstone.fitToWindow(element);
			if(isDesktop && imageType == "dicom"){
           	 plottingScale(element); 
             }

			cnt++;
		}

	}
	resizeSeriesDiv();
}